package com.bbs.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.bbs.entity.Blocks;
import com.bbs.util.DBHelp;
import com.bbs.util.RowMapper;

public class BlocksDao {
	private DBHelp<Blocks> db = new DBHelp<Blocks>();
	
	public List<Blocks> findFatherBlocks() {
		String sql = "SELECT id, NAME, pid, content FROM t_blocks WHERE pid = 0";
		return db.queryForList(sql, new BlocksMapper());
	}
	
	public List<Blocks> findByBlocksPid(int pid) {
		String sql = "SELECT id, NAME, pid, content FROM t_blocks WHERE pid = ?";
		
		return db.queryForList(sql, new BlocksMapper() , pid);
	}
	
	public Blocks findById(int id) {
		String sql = "SELECT id,NAME,pid,content FROM t_blocks WHERE id = ?";
		return db.queryForObject(sql, new BlocksMapper(), id);
	}
	
	public int findBlocksCount(int id) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT COUNT(t_article.id) ");
		sql.append("FROM t_blocks ");
		sql.append("LEFT JOIN t_article ON t_blocks.id = t_article.t_blocks_id ");
		sql.append("WHERE t_blocks.id = ? ");
		sql.append("GROUP BY t_blocks.id ");
		
		return db.queryForCount(sql.toString(), id);
	}

	public List<Blocks> findZBlocks() {
		String sql = "SELECT id, NAME, pid, content FROM t_blocks WHERE pid <> 0";
		return db.queryForList(sql, new BlocksMapper());
	}

	public void deleteById(int id) {
		String sql = "DELETE FROM t_blocks WHERE id = ?";
		db.update(sql, id);
	}
	
}
class BlocksMapper implements RowMapper<Blocks> {

	public Blocks maprow(ResultSet rs) throws SQLException {
		Blocks b = new Blocks();
		b.setId(rs.getInt("id"));
		b.setName(rs.getString("name"));
		b.setContent(rs.getString("content"));
		b.setPid(rs.getInt("pid"));
		return b;
	}
	
}
